package com.jeesuite.admin.controller.api;

import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jeesuite.admin.dao.entity.AppEntity;
import com.jeesuite.admin.dao.entity.AppconfigEntity;
import com.jeesuite.admin.dao.mapper.AppEntityMapper;
import com.jeesuite.admin.dao.mapper.AppconfigEntityMapper;
import com.jeesuite.admin.exception.JeesuiteBaseException;
import com.jeesuite.admin.util.CryptUtils;

import tk.mybatis.mapper.entity.Example;


@Controller
@RequestMapping("/api")
public class ConfigCenterApiController {

	private @Autowired AppconfigEntityMapper appconfigMapper;
	private @Autowired AppEntityMapper appMapper;
	
	@RequestMapping(value = "download_config_file", method = RequestMethod.GET)
	public void downConfigFile(HttpServletResponse response,
			                     @RequestParam(value = "appName") String appName,
			                     @RequestParam(value = "env") String env,
			                     @RequestParam(value = "version",required = false) String version,
			                     @RequestParam(value = "fileName") String fileName){
		
		Example example = new Example(AppconfigEntity.class);
		example.createCriteria().andEqualTo("name", fileName)
		                        .andEqualTo("env", env)
		                        .andEqualTo("appName", appName)
		                        .andEqualTo("version", version);
		
		List<AppconfigEntity> configList = appconfigMapper.selectByExample(example);
		if(configList == null || configList.isEmpty()){
			throw new JeesuiteBaseException(1001, "配置不存在");
		}
		OutputStream output = null;
		try {
			AppconfigEntity config = configList.get(0);
			String content = config.getContents();
			response.addHeader("Content-Disposition", "attachment;filename=" + new String(config.getName().getBytes()));
			response.addHeader("Content-Length", "" + content.length());
			output = new BufferedOutputStream(response.getOutputStream());
			response.setContentType("application/octet-stream");
			byte[] bytes = content.getBytes();
			output.write(bytes);
			output.flush();
		} catch (Exception e) {
			throw new JeesuiteBaseException(9999, "下载失败");
		}finally {			
			if(output != null){
				try {output.close(); } catch (Exception e) {}
			}
		}
	}
	
	@RequestMapping(value = "fetch_all_configs", method = RequestMethod.GET)
	public @ResponseBody Map<String, Object> downConfigFile(  @RequestParam(value = "appName") String appName,
			                     @RequestParam(value = "env") String env,
			                     @RequestParam(value = "version",required = false) String version){
		
		if(StringUtils.isBlank(version))version = "0.0.0";
		//先查全局的
		Example example = new Example(AppconfigEntity.class);
		example.createCriteria().andEqualTo("env", env)
		                        .andEqualTo("appName", "global")
		                        .andEqualTo("version", version);
		
		List<AppconfigEntity> configList = appconfigMapper.selectByExample(example);
		
		example.clear();
		example.createCriteria().andEqualTo("env", env)
		                        .andEqualTo("appName", appName)
                                .andEqualTo("version", version);

        List<AppconfigEntity> configList2 = appconfigMapper.selectByExample(example);
        if(!configList2.isEmpty())configList.addAll(configList2);
		
		if(configList == null || configList.isEmpty()){
			throw new JeesuiteBaseException(1001, "配置不存在");
		}
		
		AppEntity entity = appMapper.findByName(appName);
		String encryptKey = entity.getSecret() + env;
		
		Map<String, Object> result = new HashMap<>();
		
        for (AppconfigEntity config : configList) {
			if(config.getType() == 2){
				result.put(config.getName(), CryptUtils.decode(encryptKey, config.getContents()));
			}else{
				String[] lines = config.getContents().split("\n");
				for (String line : lines) {
					if(StringUtils.isBlank(line) || line.startsWith("#") || line.indexOf("=") < 0)continue;
					//考虑 value包含=的情况
					String key = line.substring(0, line.indexOf("=")).trim();
					String value = line.substring(line.indexOf("=") + 1).trim();
					if(StringUtils.isNotBlank(value)){	
						if(value.startsWith("${")){
							String refKey = value.substring(2, value.length() - 1).trim();
							value = (String) result.get(refKey);
							if(StringUtils.isBlank(value))continue;
						}
						result.put(key, CryptUtils.decode(encryptKey, value));
					}
				}
			}
		}
		return result;
	}

}
